"""
LAN对讲机 - 卸载程序
独立的卸载工具，通过控制面板或直接运行
"""
import os
import sys
import shutil
import winreg
import subprocess
import time
from pathlib import Path
from PyQt6.QtWidgets import QApplication, QMessageBox
from PyQt6.QtCore import QTimer


def get_install_info():
    """从注册表获取安装信息"""
    try:
        key = winreg.OpenKey(
            winreg.HKEY_CURRENT_USER,
            r"Software\Microsoft\Windows\CurrentVersion\Uninstall\LAN对讲机",
            0,
            winreg.KEY_READ
        )
        install_path = winreg.QueryValueEx(key, "InstallLocation")[0]
        winreg.CloseKey(key)
        return install_path
    except:
        # 如果从注册表读取失败，尝试从命令行参数或当前目录获取
        if len(sys.argv) > 1:
            return sys.argv[1]
        return os.path.dirname(os.path.abspath(sys.executable))


def stop_application():
    """停止运行的应用程序"""
    try:
        subprocess.run(
            ['taskkill', '/F', '/IM', 'LAN对讲机.exe'],
            capture_output=True,
            timeout=5
        )
        time.sleep(1)
        return True
    except:
        return False


def delete_shortcuts():
    """删除快捷方式"""
    errors = []
    
    # 删除桌面快捷方式
    try:
        desktop = Path.home() / "Desktop" / "LAN对讲机.lnk"
        if desktop.exists():
            desktop.unlink()
    except Exception as e:
        errors.append(f"删除桌面快捷方式失败: {e}")
    
    # 删除开始菜单快捷方式
    try:
        start_menu = Path(os.environ["APPDATA"]) / "Microsoft" / "Windows" / "Start Menu" / "Programs" / "LAN对讲机.lnk"
        if start_menu.exists():
            start_menu.unlink()
    except Exception as e:
        errors.append(f"删除开始菜单快捷方式失败: {e}")
    
    return errors


def delete_autostart():
    """删除开机自启动"""
    try:
        key = winreg.OpenKey(
            winreg.HKEY_CURRENT_USER,
            r"Software\Microsoft\Windows\CurrentVersion\Run",
            0,
            winreg.KEY_SET_VALUE
        )
        try:
            winreg.DeleteValue(key, "LAN对讲机")
        except:
            pass
        winreg.CloseKey(key)
        return True
    except Exception as e:
        return False


def delete_config():
    """删除用户配置目录"""
    try:
        config_dir = Path.home() / ".walkietalkie"
        if config_dir.exists():
            shutil.rmtree(config_dir)
        return True
    except Exception as e:
        return False


def delete_registry():
    """删除注册表项"""
    try:
        winreg.DeleteKey(
            winreg.HKEY_CURRENT_USER,
            r"Software\Microsoft\Windows\CurrentVersion\Uninstall\LAN对讲机"
        )
        return True
    except:
        return False


def create_cleanup_script(install_path):
    """创建延迟删除脚本"""
    batch_content = f'''@echo off
timeout /t 2 /nobreak >nul
rd /s /q "{install_path}" 2>nul
del "%~f0"
'''
    
    temp_bat = Path(os.environ['TEMP']) / f'uninstall_cleanup_{int(time.time())}.bat'
    with open(temp_bat, 'w', encoding='gbk') as f:
        f.write(batch_content)
    
    return str(temp_bat)


def perform_uninstall(install_path):
    """执行卸载"""
    errors = []
    
    # 1. 停止应用程序
    stop_application()
    
    # 2. 删除快捷方式
    shortcut_errors = delete_shortcuts()
    errors.extend(shortcut_errors)
    
    # 3. 删除开机自启动
    if not delete_autostart():
        errors.append("删除开机自启动失败")
    
    # 4. 删除配置目录
    if not delete_config():
        errors.append("删除配置目录失败")
    
    # 5. 删除注册表
    if not delete_registry():
        errors.append("删除注册表项失败")
    
    # 6. 创建延迟删除脚本
    cleanup_script = create_cleanup_script(install_path)
    
    return errors, cleanup_script


def main():
    """主函数"""
    app = QApplication(sys.argv)
    
    # 确认卸载
    reply = QMessageBox.question(
        None,
        "确认卸载",
        "确定要卸载 LAN对讲机 吗？\n\n这将删除程序及其所有数据。",
        QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
        QMessageBox.StandardButton.No
    )
    
    if reply != QMessageBox.StandardButton.Yes:
        sys.exit(0)
    
    # 获取安装路径
    install_path = get_install_info()
    
    if not install_path or not os.path.exists(install_path):
        QMessageBox.critical(
            None,
            "错误",
            f"无法找到安装路径：{install_path}\n\n请手动删除程序文件。"
        )
        sys.exit(1)
    
    # 执行卸载
    errors, cleanup_script = perform_uninstall(install_path)
    
    # 显示结果
    if errors:
        QMessageBox.warning(
            None,
            "卸载完成（部分失败）",
            f"LAN对讲机 已部分卸载。\n\n以下操作失败：\n" + "\n".join(errors[:5])
        )
    else:
        QMessageBox.information(
            None,
            "卸载完成",
            "LAN对讲机 已成功卸载！"
        )
    
    # 延迟启动清理脚本
    def launch_cleanup():
        try:
            subprocess.Popen(
                ['cmd', '/c', cleanup_script],
                creationflags=subprocess.CREATE_NO_WINDOW
            )
        except:
            pass
        app.quit()
    
    QTimer.singleShot(500, launch_cleanup)
    
    sys.exit(app.exec())


if __name__ == "__main__":
    main()

